//
//  HomeController.swift
//  首页
//
//  Created by smile on 2019/4/6.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//发布订阅框架
import SwiftEventBus

//主题框架
import SwiftTheme

class HomeController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //主题
        //TabBar背景颜色
        tabBar.theme_barTintColor=[COLOR_STRING_WHITE,COLOR_STRING_DARK_BLACK]
        
//        //TabBar选中高亮颜色
//        tabBar.tintColor=UIColor(hex: COLOR_PRIMARY)
        
        //TabBar选中高亮颜色
        tabBar.theme_tintColor=[COLOR_STRING_PRIMARY,COLOR_STRING_DARK_PRIMARY]
        
        //监听消息
        JMessage.add(self, with: nil)
        
        //第一次获取消息未读数
        updateMessageReadCount()
        
        //监听进入了聊天界面
        //因为当前界面不好监听界面的显示和隐藏
        //所以理论上只要进入聊天界面
        //都有可能查看了消息
        //所有这里监听这个事件
        //刷新消息未读数
        
        //当然这里最好的实现就是像其他界面
        //显示的时候监听
        //隐藏的时候去除监听
        //监听选择了话题
        SwiftEventBus.onMainThread(self, name: ON_MESSAGE_COUNT_CHANGED) { result in
            self.updateMessageReadCount()
        }
    }
    
    
    /// 在UITabBarController中
    /// viewDidAppear方法是不能监听当前控制的显示和隐藏的
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        print("HomeController viewDidAppear")
        
        print("HomeController viewDidAppear tabbar frame:\(tabBar.frame)")
    }
    
    /// 显示未读消息数
    func updateMessageReadCount() {
        //获取未读消息数
        let unreadMessageCount=MessageUtil.getUnreadMessageCount()
        
        //获取到第4个UITabBarItem
        let accountTabBarItem=tabBar.items![4]
        
        if (unreadMessageCount>0) {
            //有未读消息
            //直接设置字符串
            accountTabBarItem.badgeValue="\(unreadMessageCount)"
        }else{
            //没有未读消息
            //清除红点
            accountTabBarItem.badgeValue=nil
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension HomeController:JMessageDelegate {
    //极光聊天在线消息回调
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        updateMessageReadCount()
    }

}
